<template>
  <div v-loading="loading" class="hotel-room">
    <el-form :model="dataForm" :disabled="dataForm.trialPictureState == 1" :rules="dataRule" ref="dataForm"
      @keyup.enter.native="dataFormSubmit()" label-width="auto">

      <el-form-item label-width="0" v-if="dataForm.trialPictureState == 1">
        <el-alert title="待审核" type="warning" show-icon>
        </el-alert>
      </el-form-item>
      <el-form-item label-width="0" v-if="dataForm.trialPictureState == 3">
        <el-alert show-icon title="审核失败" type="warning" :description="dataForm.trialMsg">
        </el-alert>
      </el-form-item>

      <el-form-item label="房型标签" prop="discounts">
        <el-tag :key="tag" v-for="tag in dataForm.tagList" closable :disable-transitions="false" @close="handleClose(tag)">{{ tag }}</el-tag>
        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small">
          <el-button slot="append" icon="el-icon-plus" @click="handleInputConfirm()"></el-button>
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">添加</el-button>
      </el-form-item>

      <el-form-item label="房间设施">
        <el-checkbox-group v-model="dataForm.facilities">
          <el-checkbox v-for="(fac, index) in facility" :label="fac.name">{{ fac.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="取消规则" prop="cancelTime">
        <el-row>
          <el-col class="form-item-row">
            <el-radio v-model="dataForm.cancelRule" label="1">入住当天</el-radio>
            <el-time-select style="width: 120px;" class="el-input" v-model="dataForm.cancelTime" :picker-options="{
                start: '00:00',
                step: '00:01',
                end: '23:59'
              }"
              :default-value="dataForm.cancelTime" placeholder="选择时间"></el-time-select>
            <span class="el-span">前可取消</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="form-item-row">
            <el-radio v-model="dataForm.cancelRule" label="2">入住前&nbsp;&nbsp;&nbsp;&nbsp;</el-radio>
            <el-input-number style="width: 120px;" class="el-input" v-model="dataForm.cancelDayNum" :min="1" :max="10" label="天"></el-input-number>
            <span class="el-span">天</span>
            <el-time-select style="width: 120px;" class="el-input" v-model="dataForm.cancelTime" :picker-options="{
                start: '00:00',
                step: '00:01',
                end: '23:59'
              }"
              :default-value="dataForm.cancelTime" placeholder="选择时间"></el-time-select>
            <span class="el-span">前可取消</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="form-item-row">
            <el-radio v-model="dataForm.cancelRule" label="3">入住前&nbsp;&nbsp;&nbsp;&nbsp;</el-radio>
            <el-input-number style="width: 120px;" class="el-input" v-model="dataForm.cancelDayNum" :min="1" :max="10" label="天"></el-input-number>
            <span class="el-span">天</span>
            <el-time-select style="width: 120px;" class="el-input" v-model="dataForm.cancelTime" :picker-options="{
                start: '00:00',
                step: '00:01',
                end: '23:59'
              }"
              :default-value="dataForm.cancelTime" placeholder="选择时间"></el-time-select>
            <span class="el-span">前可取消,收取</span>
            <el-input-number style="width: 120px;" class="el-input" v-model="dataForm.deductScale" :min="1" :max="100" label="%"></el-input-number>
            <span class="el-span">%罚金，此后不可取消</span>
          </el-col>
        </el-row>
        <el-row>
          <el-radio v-model="dataForm.cancelRule" label="4">不可取消</el-radio>
        </el-row>
        <el-row>
          <el-radio v-model="dataForm.cancelRule" label="0">可取消</el-radio>
        </el-row>
      </el-form-item>

    </el-form>
    <span class="dialog-footer">
      <el-button v-if="dataForm.trialPictureState == 1" disabled>待审核</el-button>
      <el-button v-if="dataForm.trialPictureState == 2" type="primary" @click="dataFormSubmit()">{{ $t('Common.Confirm') }}</el-button>
      <el-button v-if="dataForm.trialPictureState == 3" type="primary" @click="dataFormSubmit()">重新提交</el-button>
    </span>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        inputVisible: false,
        loading: false,
        inputValue: '',
        visible: false,
        editorOption: {
          placeholder: '请填写房间描述!'
        },
        uploadAction: '',
        dialogImageUrl: '',
        dialogVisible: false,
        fileList: [],
        facility: [],
        result: [],
        dataForm: {
          id: 0,
          trialPictureState: 2,
          sellerId: '',
          sign: '',
          checkList: ['全天房'],
          facility: [],
          cancelRule: '0',
          cancelDayNum: 1,
          cancelTime: '',
          deductTime: '',
          deductScale: 10,
          name: '',
          discounts: '',
          price: '',
          area: '',
          oprice: '',
          img: '',
          floor: '',
          people: 1,
          bed: '',
          breakfast: '',
          facilities: [],
          tagList: [],
          windows: '0',
          logo: '',
          size: '',
          isRefund: '',
          totalNum: 1,
          yjState: '',
          yjCost: '',
          sort: '',
          state: '',
          classify: 1
        },
        dataRule: {
          name: [{
            required: true,
            message: '房型名字不能为空',
            trigger: 'blur'
          }],
          oprice: [{
            required: true,
            message: '门市价不能为空',
            trigger: 'blur'
          }],
          size: [{
            required: true,
            message: '床型尺寸不能为空',
            trigger: 'blur'
          }],
          area: [{
            required: true,
            message: '房间面积不能为空',
            trigger: 'blur'
          }],
          sort: [{
            required: true,
            message: '排序不能为空',
            trigger: 'blur'
          }],
          state: [{
            required: true,
            message: '房间状态不能为空',
            trigger: 'blur'
          }],
          classify: [{
            required: true,
            message: '房间类别不能为空',
            trigger: 'blur'
          }]
        }
      };
    },
    methods: {
      async submitUpload() {
        await this.$refs.upload.submit();
      },
      getFacility() {
        this.$http({
          url: this.$http.adornUrl(`/hotel/hotelfacility/list`),
          method: 'get',
          params: this.$http.adornParams({
            type: 2
          })
        }).then(({
          data
        }) => {
          this.facility = data.page.list;
        });
      },
      onEditorBlur() {},
      onEditorFocus() {
        //获得焦点事件
      },
      onEditorChange() {
        //内容改变事件
      },
      init(id) {
        Object.assign(this.$data, this.$options.data());
        this.getFacility();
        this.fileList = [];
        this.uploadAction = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`);
        this.dataForm.id = id || 0;
        this.visible = true;
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields();
          this.dataForm.tagList = [];
          if (this.dataForm.id) {
            this.loading = true;
            this.$http({
              url: this.$http.adornUrl(`/hotel/hotelroom/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              this.loading = false;
              if (data && data.code === 0) {
                this.dataForm.id = data.hotelroom.id;
                this.dataForm.facilities = data.hotelroom.facilities ? data.hotelroom.facilities.split(',') : [];
                this.dataForm.sellerId = data.hotelroom.sellerId;
                this.dataForm.sign = data.hotelroom.sign;
                this.dataForm.tagList = data.hotelroom.tagList || [];
                this.dataForm.rzTime = data.hotelroom.rzTime;
                this.dataForm.cancelRule = data.hotelroom.cancelRule + '';
                if (data.hotelroom.cancelRule == null) {
                  this.dataForm.cancelRule = '0';
                }
                this.dataForm.trialPictureState = data.hotelroom.trialPictureState,
                  this.dataForm.trialMsg = data.hotelroom.trialMsg,
                  this.dataForm.cancelDayNum = data.hotelroom.cancelDayNum;
                this.dataForm.cancelTime = data.hotelroom.cancelTime;
                this.dataForm.deductTime = data.hotelroom.deductTime;
                this.dataForm.deductScale = data.hotelroom.deductScale;
                this.$forceUpdate();
              }
            });
          }
        });
      },
      // 表单提交
      async dataFormSubmit() {
        // await this.$refs.upload.submit();
        let icons = [];
        if (this.dataForm.facilities) {
          icons = this.dataForm.facilities
            .filter(f => f && f !== '')
            .map(f => {
              const fac = this.facility.find(i => i.name === f);
              return fac ? fac.icon : '';
            });
        }
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/hotel/hotelroom/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                id: this.dataForm.id || undefined,
                facilities: this.dataForm.facilities
                  .filter(f => f && f !== '')
                  .reduce((p, n) => {
                    p += n + ',';
                    return p;
                  }, ''),
                facilitiesIcon: icons.reduce((p, n) => {
                  p += n + ',';
                  return p;
                }, ''),
                sellerId: this.dataForm.sellerId,
                sign: this.dataForm.sign,
                discounts: this.dataForm.discounts ? 1 : 0,
                tagList: this.dataForm.tagList,
                rzTime: this.dataForm.rzTime,
                cancelRule: this.dataForm.cancelRule,
                cancelDayNum: this.dataForm.cancelDayNum,
                cancelTime: this.dataForm.cancelTime,
                deductTime: this.dataForm.deductTime,
                deductScale: this.dataForm.deductScale
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: this.$t('Common.OperationSuccessful'),
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.init(this.dataForm.id)
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        });
      },
      handleAvatarSuccess(res, file) {
        this.dataForm.logo = res.url;
      },
      handleImageSuccess(res, file, fileList) {
        let url = [];
        // 对于新增操作
        fileList.forEach(item => {
          const {
            response
          } = item;
          if (response && response.code === 0 && response.msg === 'success') {
            url.push(response.url);
          }
        });
        // 对于修改操作
        if (this.dataForm.id) {
          const imgs = this.dataForm.img.split(',');
          url = [...url, ...imgs];
        }
        this.dataForm.img = url.join(',');
      },
      handleClose(tag) {
        this.dataForm.tagList.splice(this.dataForm.tagList.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.dataForm.tagList.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      handleOnCHange(file, fileList) {},
      handleRemove(file, fileList) {
        /**
         * handleRemove只针对修改操作，对已存在的图片进行删除，新增实际上可以不定义此函数
         * 以下条件说明：
         * 用于限制已经上传的图片是否可被删除
         * 去掉注释则为：以前上传的图片不允许在修改进行删除
         * file.status：success已经上传到服务器的图片
         * file.status：ready从硬盘读取但是未上传到服务器的图片
         */
        // if (file.status === 'success') return;
        // uid可能相同，但是url基本不可能相同，但了保险，做一个"&&"操作
        const index = this.fileList.findIndex(item => item.uid === file.uid && item.url === file.url);
        // 针对已经上传了的图片进行删除掉，同时更新this.dataForm.img，以便“真正的删除”
        if (this.dataForm.id && index > -1) {
          this.fileList.splice(index, 1);
          const url = [];
          this.fileList.map(item => {
            url.push(item.url);
          });
          this.dataForm.img = url.join(',');
        }
        // 删除图片并更新列表
        this.fileList = fileList;
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
      }
    }
  };
</script>
<style lang="less" scoped>


  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }

  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }

  .updaloe-row {
    display: flex;
    align-items: center;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 190px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .el-dialog__wrapper /deep/ .el-dialog {
    width: 80%;
  }

  @media only screen and (max-width: 1180px) {
    .el-dialog__wrapper /deep/ .el-dialog {
      width: 100%;
    }
  }
</style>
